package com.zhang.teachingcommunity_spring.controller.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.zhang.teachingcommunity_spring.excption.businessSystemException;
import com.zhang.teachingcommunity_spring.mapper.entity.User;
import com.zhang.teachingcommunity_spring.service.UserService;
import com.zhang.teachingcommunity_spring.utils.status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ProjectInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if(StrUtil.isAllBlank(token)){
            throw new businessSystemException("用户不存在，请重新登录!", status.STATUS_401);
        }
        String id;
        try {
            id = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new businessSystemException("token不正确，请不要通过非法手段创建token",status.STATUS_401);
        }
        User user = userService.geById(Integer.valueOf(id));
        //查询数据库，看看是否存在此用户，方法要自己写
        if (user.getUserId() == null) {
            throw new businessSystemException("用户不存在，请重新登录",status.STATUS_401);
        }
        // 验证 token
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getUsername())).build();
            jwtVerifier.verify(token);
        }catch (TokenExpiredException e) {
            throw new businessSystemException("token过期或不正确，请重新登录",status.STATUS_401);
        }
            return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
